package spuFile

import (
	"context"
	"errors"
	"fmt"
	"github.com/google/uuid"
	"github.com/kuangshp/go-utils/k"
	"github.com/spf13/cast"
	"github.com/tealeg/xlsx"
	"github.com/zeromicro/go-zero/core/logx"
	"gorm.io/gorm"
	"insighttracking/apps/admin/auth"
	"insighttracking/apps/admin/internal/svc"
	"insighttracking/query/model"
	"insighttracking/query/service"
	"io"
	"net/http"
	"os"
	"path"
	"time"
)

type ImportExcelApiLogic struct {
	logx.Logger
	ctx     context.Context
	svcCtx  *svc.ServiceContext
	Request *http.Request
}

func NewImportExcelApiLogic(ctx context.Context, svcCtx *svc.ServiceContext, request *http.Request) *ImportExcelApiLogic {
	hostname, _ := os.Hostname()
	return &ImportExcelApiLogic{
		Logger: logx.WithContext(ctx).WithCallerSkip(0).WithFields(
			logx.Field("Log_UUID", uuid.New().String()),
			logx.Field("hostname", hostname)),
		ctx:     ctx,
		svcCtx:  svcCtx,
		Request: request,
	}
}

func (l *ImportExcelApiLogic) ImportExcelApi() (resp string, err error) {
	// todo: add your logic here and delete this line
	accountInfo, err := auth.GetAccountInfo(l.svcCtx, l.Request)
	if err != nil {
		return "", err
	}
	file, handler, err := l.Request.FormFile("file")
	if err != nil {
		return "", err
	}
	defer file.Close()
	fileType := path.Ext(handler.Filename)
	if !k.IsContains([]string{".xlsx", ".xls"}, fileType) {
		return "", errors.New("只能是.xlsx,.xls其中一种格式")
	}
	workDir, _ := os.Getwd()
	dst := path.Join(workDir, handler.Filename)
	f, err := os.OpenFile(dst, os.O_WRONLY|os.O_CREATE, 0666)
	if err != nil {
		fmt.Println("本地创建失败")
		return "", errors.New("上传文件失败")
	}
	defer f.Close()
	io.Copy(f, file)
	// 读取Excel文件内容
	xlFile, err := xlsx.OpenFile(dst)
	if err != nil {
		fmt.Println("读取excel失败", err)
		return "", errors.New("上传失败")
	}
	// 单独设置超时时间
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	for _, sheet := range xlFile.Sheets {
		fmt.Println("开始读取数据")
		for index, row := range sheet.Rows { // 循环行
			if index > 0 {
				//for _, cell := range row.Cells { // 循环每列
				//	// 获取单元格的值并输出
				//	fmt.Printf("%s\t", cell.String())
				//
				//}
				if row.Cells[0].String() == "" && row.Cells[1].String() == "" && row.Cells[2].String() == "" && row.Cells[3].String() == "" && row.Cells[4].String() == "" && row.Cells[5].String() == "" {
					break
				}
				categoryName := row.Cells[1].String()
				var categoryId int64
				if categoryName != "" {
					categoryEntity, err := service.CategoryService.GetByNameApi(ctx, accountInfo.EnterpriseId, categoryName)
					if errors.Is(err, gorm.ErrRecordNotFound) {
						// 创建分类
						categoryData := model.CategoryEntity{
							EnterpriseID: accountInfo.EnterpriseId, // 关联到enterprise表主键id
							Name:         categoryName,             // 分类名称
							Sort:         1,                        // 排序
						}
						if err = service.CategoryService.CreateApi(ctx, &categoryData); err != nil {
							continue
						} else {
							categoryId = categoryData.ID
						}
					} else {
						categoryId = categoryEntity.ID
					}
				}
				spuName := row.Cells[2].String()
				brandName := row.Cells[3].String()
				var brandId int64
				if brandName != "" {
					brandEntity, err := service.BrandService.GetByNameApi(ctx, accountInfo.EnterpriseId, brandName)
					if errors.Is(err, gorm.ErrRecordNotFound) {
						brandData := model.BrandEntity{
							EnterpriseID: accountInfo.EnterpriseId, // 关联到enterprise表主键id
							Name:         brandName,                // 分类名称
							Sort:         1,                        // 排序
						}
						if err = service.BrandService.CreateApi(ctx, &brandData); err != nil {
							continue
						} else {
							brandId = brandData.ID
						}
					} else {
						brandId = brandEntity.ID
					}
				}
				specName := row.Cells[4].String()
				unitName := row.Cells[5].String()
				var unitId int64
				if unitName != "" {
					unitEntity, err := service.UnitService.GetByNameApi(ctx, accountInfo.EnterpriseId, brandName)
					if errors.Is(err, gorm.ErrRecordNotFound) {
						unitData := model.UnitEntity{
							EnterpriseID: accountInfo.EnterpriseId, // 关联到enterprise表主键id
							Name:         unitName,                 // 分类名称
							Sort:         1,                        // 排序
						}
						if err = service.UnitService.CreateApi(ctx, &unitData); err != nil {
							continue
						} else {
							unitId = unitData.ID
						}
					} else {
						unitId = unitEntity.ID
					}
				}
				fmt.Println("分类:", categoryName, "名称:", spuName, "品牌:", brandName, "规格:", specName, "单位:", unitName)
				// 创建商品
				if err = service.SpuService.CreateApi(ctx, &model.SpuEntity{
					EnterpriseID:   accountInfo.EnterpriseId,  // 关联到enterprise表主键id
					SpuType:        0,                         // 商品类型,0表示基础商品,1表示加工商品
					Name:           spuName,                   // 商品名称
					CategoryID:     categoryId,                // 商品分类,只保存最后一级的
					CategoryName:   categoryName,              // 单位分类名称
					CategoryIDList: cast.ToString(categoryId), // 分类列表,多个用英文,拼接
					UnitID:         unitId,                    // 单位,关联到unit表主键id
					BrandID:        brandId,                   // 品牌id
					Spec:           specName,                  // 商品规格
				}); err != nil {

				}
				//time.Sleep(5 * time.Second)
			}
		}
	}
	if err = os.Remove(dst); err != nil {
		fmt.Println("删除文件失败", err)
	}
	fmt.Println(dst, "?")
	return "上传成功", nil
}
